import java.applet.Applet;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

import javax.imageio.ImageIO;


@SuppressWarnings("serial")
public class OBAGHSApplet extends Applet implements Runnable {
	BufferedImage background;
	int xSize;
	int ySize;
	ArrayList<Stop> stops = new ArrayList<Stop>();
	Thread runner;
	
	public void init() {
		// TODO Set x & y sizes
		xSize = 1000;
		ySize = 1000;
		setSize(xSize, ySize);
		try {
			background = ImageIO.read(new File("background.jpg"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			setStopList();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		runner = new Thread(this);
		runner.start();		
	}
	
	public void paint(Graphics g) {
		getGraphics().drawImage(background, 0, 0, xSize, ySize, null);
		drawStopBoxes();
	}
	
	public void update(Graphics g) {
		paint(g);
	}
	
	private void setStopList() throws FileNotFoundException {
		Scanner fileScan = new Scanner(new File("stops.txt"));
		while(fileScan.hasNext()) {
			int tempID = fileScan.nextInt();
			fileScan.nextLine();
			String tempName = fileScan.nextLine();
			ArrayList<Integer> tempRoutes = new ArrayList<Integer>();
			while(fileScan.hasNextInt())
				tempRoutes.add(fileScan.nextInt());
			String tempDir = fileScan.next();
			fileScan.nextLine();
			int tempX = fileScan.nextInt();
			int tempY = fileScan.nextInt();
			fileScan.nextLine();
			stops.add(new Stop(tempID, tempName, tempRoutes, tempDir, tempX, tempY, getGraphics()));
		}
	}

	@Override
	public void run() {
		while(true) {
			createStopBoxes();
			repaint();
			drawBuses();
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void drawBuses() {
		// TODO Draw buses in their current locations. Priority: low
	}

	private void createStopBoxes() {
		//Clear SBE ArrayLists
		for (Stop s : stops)
			s.clearSbes();
		
		// Add header SBEs
		for (Stop s : stops) {
			s.sbesAdd(new StopBoxHeaderEntry(s.getStopID(), s.getCustomName(), s.getDirection()));
			s.sbesAddArrivals();
		}
	}

	private void drawStopBoxes() {
		for (Stop s : stops) {
			s.drawStopBoxes();
		}
	}


}
